<!-- 品牌管理 -->
<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button
          v-if="$hasBP('btn.Trademark.add')"
          type="primary"
          size="default"
          icon="el-icon-plus"
          @click="add"
        >添加</el-button>
      </div>
      <el-table :data="TrademarkList" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="logoUrl" label="图片logo">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" width="50px" height="50px">
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="edit(row)"
            >修改</el-button>

            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="delTrademark(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :style="{ marginTop: '20px' }"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="prev, pager, next, jumper, sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-dialog
        :title="tmInfo.id ? '修改品牌' : '新增品牌'"
        :visible.sync="dialogVisible"
        width="60%"
      >
        <el-form
          ref="formEl"
          label-width="80px"
          :inline="false"
          :model="tmInfo"
        >
          <el-form-item
            label="品牌名称"
            prop="tmName"
            :rules="[
              { required: true, message: '品牌名称不能为空', trigger: 'blur' },
            ]"
          >
            <el-input v-model="tmInfo.tmName" />
          </el-form-item>
          <el-form-item
            label="品牌logo"
            prop="logoUrl"
            :rules="[
              { required: true, message: '品牌logo不能为空', trigger: 'blur' },
            ]"
          >
            <el-upload
              class="avatar-uploader"
              :action="`${baseUrl}/admin/product/upload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </el-form>

        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdateTrademark">{{
              tmInfo.id ? "修改" : "新增"
            }}</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reqGetTrademarkList,
  reqDeleteTrademark,
  reqUpdataTrademark,
  reqAddTrademark
} from '@/api/Trademark.js'

export default {
  name: 'Trademark',
  data() {
    return {
      TrademarkList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      imageUrl: '',
      tmInfo: {
        tmName: '',
        logoUrl: ''
      }
    }
  },
  mounted() {
    this.getTrademarkList()
  },

  methods: {
    async getTrademarkList() {
      const TrademarkList = await reqGetTrademarkList(
        this.currentPage,
        this.pageSize
      )
      // console.log(TrademarkList);
      this.TrademarkList = TrademarkList.data.records
      this.currentPage = TrademarkList.data.current
      this.pageSize = TrademarkList.data.size
      this.total = TrademarkList.data.total
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getTrademarkList()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getTrademarkList()
    },

    // 添加
    add() {
      // console.log(this.$refs.formEl);
      // this.$nextTick(() => {
      //   this.$refs.formEl.clearValidate();
      // });
      this.dialogVisible = true
      // 重置收集用户表单的tmInfo
      this.tmInfo = {
        tmName: '',
        logoUrl: ''
      }
      this.imageUrl = ''
    },

    // 添加/修改
    async addOrUpdateTrademark() {
      // 先对表单进行整体校验????
      try {
        await this.$refs.formEl.validate()
      } catch (e) {
        return
      }
      // this.$refs['formEl'].resetFields();
      // 有id：修改
      if (this.tmInfo.id) {
        // console.log(this.tmInfo);
        await reqUpdataTrademark(this.tmInfo)
        // 关闭弹窗
        this.dialogVisible = false
        // 重新请求
        this.getTrademarkList()
      } else {
        // 没有id：新增
        await reqAddTrademark(this.tmInfo)
        // 关闭弹窗
        this.dialogVisible = false
        // 重新请求
        this.getTrademarkList()
      }
    },
    edit(row) {
      // console.log(this.$refs.formEl);
      // this.$nextTick(() => {
      //   this.$refs.formEl.clearValidate();
      // });
      this.dialogVisible = true
      // 回填数据(拷贝,否则tmInfo和row是同一个地址,tmInfo只要发生改变,则row直接就改变)
      this.tmInfo = { ...row }
      this.imageUrl = row.logoUrl
    },
    // 修改
    handleAvatarSuccess(response, uploadFile) {
      this.imageUrl = URL.createObjectURL(uploadFile.raw)
      // console.log(response.data);
      // 收集地址
      this.tmInfo.logoUrl = response.data
    },
    beforeAvatarUpload(rawFile) {
      if (!rawFile.type.startsWith('image/')) {
        this.$message.error('上传的不是图片类型！！！')
        return false
      } else if (rawFile.size / 1024 / 1024 > 10) {
        this.$message.error('上传图片的大小不能大于10MB!')
        return false
      }
      return true
    },
    // 删除
    async delTrademark(id) {
      try {
        await reqDeleteTrademark(id)
        this.getTrademarkList()
      } catch (e) {
        this.$message('删除失败' + e.message)
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
